from django.contrib.auth.models import AbstractUser
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from django.utils.html import format_html


# Create your models here.


class User(AbstractUser):
    birthday = models.DateTimeField(verbose_name="生日", null=True)
    age = models.IntegerField(verbose_name="年龄", null=True)
    gender_choices = ((1, '男'), (2, '女'), (3, "不愿透露"))
    gender = models.IntegerField(verbose_name="性别", choices=gender_choices, default=1)
    image = models.ImageField(blank=True, null=True, verbose_name="个人头像")
    nickname = models.CharField(max_length=50, default="", null=True, verbose_name="用户昵称")

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = verbose_name

    def image_tag(self):
        if self.image:
            return format_html('<img src="{}" width="50" height="50" />'.format(self.image.url))
        return ""

    image_tag.short_description = 'Image'  # 在管理界面列标题显示为 "Image"


class BlogCategory(models.Model):
    name = models.CharField(max_length=200, verbose_name='分类名称')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '博客分类'
        verbose_name_plural = verbose_name


class Blog(models.Model):
    title = models.CharField(max_length=200, verbose_name='标题')
    content = models.TextField(verbose_name='内容')
    pub_time = models.DateTimeField(auto_now_add=True, verbose_name="发布时间")
    category = models.ForeignKey(BlogCategory, on_delete=models.CASCADE, verbose_name='分类')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='发布作者')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = '博客'
        verbose_name_plural = verbose_name
        ordering = ['-pub_time']


class BlogComment(models.Model):
    content = models.TextField(verbose_name='评论内容')
    pub_time = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments', verbose_name='所属博客')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='发布作者')

    def __str__(self):
        return self.content

    class Meta:
        verbose_name = '博客评论'
        verbose_name_plural = verbose_name
        ordering = ['-pub_time']
